package net.csdra.wenhua.nanan.qiandao.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import info.didyapp.weixin.UserAccessTokenResponse;
import info.didyapp.weixin.UserInfoResponse;
import info.didyapp.weixin.WechatAdapter;
import net.csdra.wenhua.nanan.qiandao.domain.CheckIn;
import net.csdra.wenhua.nanan.qiandao.domain.User;
import net.csdra.wenhua.nanan.qiandao.service.AdminService;
import net.csdra.wenhua.nanan.qiandao.service.CheckInService;
import net.csdra.wenhua.nanan.qiandao.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by Didy on 2016-02-15.
 */
@Controller
@RequestMapping("/qiandao")
public class WeixinController {

    private static final Logger log = LoggerFactory.getLogger(WeixinController.class);

    Boolean debug = true;
    @Value("${weixin.logincallback}")
    String loginCallback;
    @Value("${weixin.subscribeRequired}")
    boolean subscribeRequired;

    @Autowired
    CheckInService checkInService;
    @Autowired
    UserService userService;
    @Autowired
    AdminService adminService;
    @Autowired
    WechatAdapter wechatAdapter;

    @RequestMapping("")
    public String getIndex(HttpSession session, WebRequest request) {
        String currentUserId = (String) session.getAttribute("CURRENT_USER_ID");
        System.out.println("msf" + currentUserId);
        if (currentUserId == null) {
            if (Boolean.TRUE.equals(debug) && request.getParameter("currentUserId") != null) {
                currentUserId = request.getParameter("currentUserId");
                System.out.println("1. CURRENT_USER_ID" + currentUserId);
                session.setAttribute("CURRENT_USER_ID", currentUserId);
                return "/index.html";
            }
            throw new AccessDeniedException("请先登录");
        } else {
            return "/index.html";
        }
    }

    @RequestMapping("/subscribe")
    public String getIndex() {
        return "/qiandao/index-subscribe.html";
    }

    @RequestMapping(value = "/weixincallback")
    public String weixinCallback(HttpSession session, String code, String state) throws IOException {
        UserAccessTokenResponse userAccessToken = wechatAdapter.getUserAccessToken(code);
        log.debug("Got userAccessToken: {}", userAccessToken);
        System.out.println("msf1:"+userAccessToken.getOpenId());
        String openId = userAccessToken.getOpenId();
        User user = adminService.getUserByWeixinId(openId);
        if (user == null) {     // 第一次登录,初始化用户数据
            String userInfo = "";
            try {
                UserInfoResponse userInfoResponse = wechatAdapter.getUserInfo(openId);
                userInfo = new ObjectMapper().writeValueAsString(userInfoResponse);
            } catch (IOException e) {
                throw new RuntimeException("getUserInfo IOException:", e);
            }
            UserService.CreateUser createUser = new UserService.CreateUser();
            createUser.setWeixinId(openId);
            createUser.setUserInfo(userInfo);
            userService.createUser(createUser);
        }
//        if (subscribeRequired) {
//            if (openId == null) {
//                return "redirect:/qiandao/subscribe?" + new Date().getTime();
//            }
//            UserInfoResponse userInfo = wechatAdapter.getUserInfo(openId);
//            log.debug("Got userInfo: {}", userInfo);
//            if (!Objects.equals(userInfo.getSubscribe(), 1)) {
//                return "redirect:/qiandao/subscribe?" + new Date().getTime();
//            }
//        }
        log.info("Set user as logged in: {}", openId);
        session.setAttribute("CURRENT_USER_ID", openId);
        return "redirect:/weixin-qiandao/";
    }

    @ExceptionHandler(AccessDeniedException.class)
    public void handleAccessDeniedException(AccessDeniedException ex, HttpServletResponse response, WebRequest
            request) throws IOException {
        String loginUrl = wechatAdapter.getLoginUrl(loginCallback, "qiandao", subscribeRequired);
        log.debug("Got loginUrl: {}", loginUrl);
        System.out.println("login:" + loginUrl);
        response.sendRedirect(loginUrl);
    }

}
